from flask import Flask, request, send_file, make_response
from flask_restful import Api, Resource
from flask_cors import CORS
import ri

DEBUG = True

app = Flask(__name__)
cors = CORS()
cors.init_app(app)
api = Api(app)


# 上传图片进行处理，返回处理后的图片
class upload_image(Resource):
    def get(self):
        return

    def put(self):
        return

    def post(self):
        # 获取文件  获取必要参数
        print(request)
        image_file = request.files['image']
        picture_high = request.form['height']
        picture_wide = request.form['width']
        # 保存文件 image_file.filename为文件名
        image_file.save(ri.picture_path + image_file.filename)

        print(image_file.filename,picture_high,picture_wide)
        # 缩放图片
        new_image = ri.reduce_imageSize(image_file.filename, int(picture_high), int(picture_wide))
        image_file.close()
        print(new_image)

        response = make_response(send_file(ri.picture_path+new_image))
        response.headers["Content-Disposition"] = f"{new_image}"
        response.headers["Content-Type"] = "application/octet-stream"
        response.access_control_expose_headers = "Content-Disposition"
        # 返回处理后的图片的路径
        return response
        # return send_file(ri.picture_path+new_image)

    def delete(self):
        return

class index(Resource):
    def get(self):
        return "success"


# 添加资源
api.add_resource(upload_image, '/upload_image')
api.add_resource(index, '/')

# 懂得都懂
if __name__ == '__main__':
    app.run(port=8080, host="127.0.0.1", debug=DEBUG)